<?php
	set_include_path('system'.PATH_SEPARATOR.'templates');
	require_once('DatabaseUtility.php');

	$stype = $_GET['stype'];
	$org = $_GET['org'];
	$ref = $_GET['ref'];
	$acc = $_GET['acc'];
	$desc = $_GET['desc'];
	$seq = strtolower($_GET['seq']);
	
	$gaSql = getGaSql();
	
	// Select distinct or not
	$distinct = false;
	
	/* Special cases for search */
	if(empty($stype) || $stype == "pro_s") {
		/* Array of database columns which should be read and sent back to DataTables. Use a space where
		 * you want to insert a non-database field (for example a counter or static image)
		 */
		$aColumns = array('id', 'annotation', 'latin');
		
		/* Indexed column (used for fast and accurate table cardinality) */
		$sIndexColumn = "id";
		
		/* DB table to use */
		$sTable = "protein,organism";
		
		$sJoinCondition = "protein.organism=organism.label";
		$sWhere = "WHERE ".$sJoinCondition;
	
		/* Other conditions */
		if(!empty($org)) {
			$sWhere .= " AND organism='$org'";
		}
		if(!empty($ref)) {
			$sWhere .= " AND EXISTS (SELECT * from proteinDataSourceRelation WHERE proteinDataSourceRelation.protein=protein.id AND proteinDataSourceRelation.datasource='$ref')";
		}
		if(!empty($acc)) {
			$sWhere .= " AND id IN (SELECT p3dbId FROM idMapping WHERE lower(otherId) LIKE '%$acc%')";
		}
		if(!empty($desc)) {
			$sWhere .= " AND lower(annotation) LIKE '%$desc%'";
		}
	} else if($stype == "pep_s") {
		$distinct = true;
		$aColumns = array('phosphoSequence', 'location', 'protein.id', 'annotation', 'latin');
		$sIndexColumn = "protein.id";
		$sTable = "peptide,protein,organism";
		$sJoinCondition = "peptide.protein=protein.id AND protein.organism=organism.label";
		$sWhere = "WHERE ".$sJoinCondition." AND lower(peptide.sequence) LIKE '%$seq%'";
		
		if(!empty($org)) {
			$sWhere .= " AND '$org' IN (SELECT organism FROM protein WHERE protein.id=peptide.protein)";
		}
		if(!empty($ref)) {
			$sWhere .= " AND '$ref' IN (SELECT dataSource FROM mass WHERE mass.id=peptide.mass)";
        }
	}	
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	/* 
	 * MySQL connection
	 */
	$gaSql['link'] =  mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) or
		die( 'Could not open connection to server' );
	
	mysql_select_db( $gaSql['db'], $gaSql['link'] ) or 
		die( 'Could not select database '. $gaSql['db'] );
	
	
	/* 
	 * Paging
	 */
	$sLimit = "";
	if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
	{
		$sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
			mysql_real_escape_string( $_GET['iDisplayLength'] );
	}
	
	
	/*
	 * Ordering
	 */
	if ( isset( $_GET['iSortCol_0'] ) )
	{
		$sOrder = "ORDER BY  ";
		for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
		{
			if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
			{
				$sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
				 	".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
			}
		}
		
		$sOrder = substr_replace( $sOrder, "", -2 );
		if ( $sOrder == "ORDER BY" )
		{
			$sOrder = "";
		}
	}
	
	
	/* 
	 * Filtering
	 * NOTE this does not match the built-in DataTables filtering which does it
	 * word by word on any field. It's possible to do here, but concerned about efficiency
	 * on very large tables, and MySQL's regex functionality is very limited
	 */
	if ( $_GET['sSearch'] != "" )
	{
		if(empty($sWhere)) {
			$sWhere = "WHERE (";
		} else {
			$sWhere .= " AND (";
		}
		for ( $i=0 ; $i<count($aColumns) ; $i++ )
		{
			$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
		}
		$sWhere = substr_replace( $sWhere, "", -3 ).')';
	}
	
	/* Individual column filtering */
	for ( $i=0 ; $i<count($aColumns) ; $i++ )
	{
		if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
		{
			if ( $sWhere == "" )
			{
				$sWhere = "WHERE ";
			}
			else
			{
				$sWhere .= " AND (";
			}
			$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%') ";
		}
	}
	
	
	/*
	 * SQL queries
	 * Get data to display
	 */
	$sQuery = "
		SELECT".(($distinct)? " DISTINCT" : "")." SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
		FROM   $sTable
		$sWhere
		$sOrder
		$sLimit
	";
	
	$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
	
	/* Data set length after filtering */
	$sQuery = "
		SELECT FOUND_ROWS()
	";
	$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
	$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
	$iFilteredTotal = $aResultFilterTotal[0];
	
	/* Total data set length */
	$sQuery = "
		SELECT COUNT(".$sIndexColumn.")
		FROM   $sTable
		".(($sJoinCondition != "")? "WHERE $sJoinCondition" : "")
	;
	$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
	$aResultTotal = mysql_fetch_array($rResultTotal);
	$iTotal = $aResultTotal[0];
	
	/*
	 * Output
	 */
	$output = array(
		"sEcho" => intval($_GET['sEcho']),
		"iTotalRecords" => $iTotal,
		"iTotalDisplayRecords" => $iFilteredTotal,
		"aaData" => array()
	);
	
	while ( $aRow = mysql_fetch_array( $rResult ) )
	{
		$row = array();
		//add link to protein/peptide page
		if(empty($stype) || $stype == 'pro_s'){
			$protId = $aRow['id'];
			$row[] = '<a class="button" href="protein.php?id='.$protId.'&ref='.$ref.'">Details</a>';
		} else if ($stype == 'pep_s') {
			$protId = $aRow['id'];
			$loc = $aRow['location'];
			$linkformat = str_replace('#', '%23', $aRow['phosphoSequence']);
			$row[] = '<a class="button" href="peptide.php?pnrseq='.$linkformat.'&pro='.$protId.'&loc='.$loc.'">Details</a>';
		}
		for ( $i=0 ; $i<count($aColumns) ; $i++ )
		{
			if ( $aColumns[$i] == 'location' || $aColumns[$i] == 'protein.id' || $aColumns[$i] == 'id' )
			{
				/* Do nothing */
			}
			else if ( $aColumns[$i] == "version" )
			{
				/* Special output formatting for 'version' column */
				$row[] = ($aRow[$aColumns[$i]]=="0") ? '-' : $aRow[$aColumns[$i]];
			}
			else if ( $aColumns[$i] == "phosphoSequence" )
			{
				/* Special output formatting for 'peptide' column*/
				$array = str_split(strtoupper($seq));
				$seqChar = '';
				foreach($array as $char) {
					$seqChar .= $char.'#?';                                                                                                                                      
				}
				$aRow[$aColumns[$i]] = preg_replace('/('.$seqChar.')/','<span class="seq_match">\1</span>',strtoupper($aRow[$aColumns[$i]]));
				$aRow[$aColumns[$i]] = preg_replace('/(.)#/','<span class="seq_pep ui-corner-all">\1</span>',$aRow[$aColumns[$i]]);
				$row[] = '<span class="sequence">'.$aRow[$aColumns[$i]].'</span>';
			}
			else if ( $aColumns[$i] == "annotation" )
			{
				/* Special output formatting for 'annotation' column*/
				$protId = $aRow['id'];
				$accessions = getXref($protId);
				$desc = '';
				foreach($accessions as $accession){
					$desc .= '<a href="protein.php?id='.$protId.'&ref='.$ref.'">'.$accession.'</a>,&nbsp; ';
				}
				
				if(!empty($aRow['annotation'])) {
					$desc .= '<br />'.$aRow['annotation'];
				}
				$row[] = $desc;
			}
			else if ( $aColumns[$i] == "latin" )
			{
				$row[] = '<i>'.$aRow[$aColumns[$i]].'</i>';
			}
			else if ( $aColumns[$i] != ' ' )
			{
				/* General output */
				$row[] = $aRow[$aColumns[$i]];
			}
		}
		$output['aaData'][] = $row;
	}
	
	print json_encode( $output );
?>